package com.financing.wap.web.controller.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.MessageJpushUserPhoneAliasDTO;
import com.financing.wap.dto.ProjectLikeDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFaNoticeService;
import com.financing.wap.service.IMessageJpushUserPhoneAliasService;
import com.financing.wap.service.INewsService;
import com.financing.wap.service.IProjectLikeService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.vo.FaNoticeVO;
import com.financing.wap.vo.ProjectLikeVO;
import com.financing.wap.vo.ProjectSubVO;
import com.financing.wap.web.controller.BaseController;

@Controller("apiFaNoticeController")
@RequestMapping("/api/notice")
public class FaNoticeController extends BaseController {

	@Autowired
	private IFaNoticeService faNoticeService;
	@Autowired
	private IProjectLikeService projectLikeService;
	@Autowired
	private INewsService newsService;
	@Autowired
	private IMessageJpushUserPhoneAliasService messageJpushUserPhoneAliasService;
	/**
	 * 根据Fa获取所有的消息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryOrderNoticeByFa")
	public ResultMap findNoticeByFa(HttpServletRequest request, HttpServletResponse response, FaNoticeVO faNotice, Pager pager) {
		ResultMap result = new ResultMap();
		
		List<FaNoticeVO> list = null;
		try {
			faNotice.setStart(pager.getStartIndex());
			pager.setTotalCount(faNoticeService.getFaOrderNoticeByFaCount(faNotice));
			
			list = faNoticeService.getFaOrderNoticeByFa(faNotice);
			// 将该用户下该类消息标为已读状态
			faNoticeService.readFaNoticeByFa(faNotice);
		} catch (Exception e) {
			log.error("findNoticeByFa error:", e);
		}

		result.setAttribute("list", list);
		result.setAttribute("pager", pager);
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

		return result;
	}
	
	@ResponseBody
	@RequestMapping("queryNoticeDate")
	public ResultMap findNoticeDateByFa(HttpServletRequest request, HttpServletResponse response) {
		ResultMap result = new ResultMap();
		try {
			
			UserDTO user = getSession(true).getUser();

			Map<String, Object> paramMap = new HashMap<String, Object>();

			result.setAttribute("noticeCount",new Long(0));
			result.setAttribute("jingJiaCount",new Long(0));
			result.setAttribute("newsCount",new Long(0));
			result.setAttribute("jPushCount",new Long(0));
            result.setAttribute("jPushShopCount",new Long(0));
			
			Map<String, Object> resultMap = new HashMap<String, Object>();
			if(user != null && user.getId()!=null){	//未登录不显示 交易通知 竞价通知
				// 交易通知 不含竞价
				String faId = user.getId();
				paramMap.put("faId", faId);
				
				resultMap = faNoticeService.getFaOrderNoticeUpdateDateByFa(paramMap);
				if(null != resultMap){
					result.setAttribute("noticeTitle", null == resultMap.get("title")?null:resultMap.get("title"));
					result.setAttribute("noticeDate", null == resultMap.get("date")?null:resultMap.get("date"));
					result.setAttribute("noticeCount", null == resultMap.get("count")?null:resultMap.get("count"));
				}
				// 竞价通知
				paramMap.put("type", "09");
				resultMap = faNoticeService.getFaOrderNoticeUpdateDateByFa(paramMap);
				if(null != resultMap){
					result.setAttribute("jingJiaTitle", null == resultMap.get("title")?null:resultMap.get("title"));
					result.setAttribute("jingJiaDate", null == resultMap.get("date")?null:resultMap.get("date"));
					result.setAttribute("jingJiaCount", null == resultMap.get("count")?null:resultMap.get("count"));
				}
                // 根据用户查询出绑定的设备标示
                MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
                dto.setFpUserId(faId);
                MessageJpushUserPhoneAliasDTO phoneAlias = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
                if(null != phoneAlias ){
                	//接收参数
                	String fpJpushMsgType = request.getParameter("jMsgTypes");
                	
                	paramMap.put("fpJpushMsgType",fpJpushMsgType);
                	
                    paramMap.put("msgRec",phoneAlias.getFpJpushAlias());

                    log.info("queryNoticeDate msgRec :"+phoneAlias.getFpJpushAlias());
                }
                // 极光全员推送消息列表-店铺消息
                resultMap = newsService.getJPushListShopUpdateDate(paramMap);
                if(null != resultMap){
                    result.setAttribute("jPushShopTitle", null == resultMap.get("title")?null:resultMap.get("title"));
                    result.setAttribute("jPushShopDate", null == resultMap.get("date")?null:resultMap.get("date"));
                    result.setAttribute("jPushShopCount", null == resultMap.get("count")?null:resultMap.get("count"));
                }

			}else{
				
				log.info("queryNoticeDate request.getCookies begin!");
				Cookie[] cookies = request.getCookies();
				String jpush_alias = "";
				if(cookies != null){
					for(Cookie cookie : cookies ){
						if(Constants.JPUSH_ALIAS.equals(cookie.getName())){
							jpush_alias = cookie.getValue();
						}
					}
				}
				log.info("queryNoticeDate JPUSH_ALIAS:"+jpush_alias);
				if(StringUtils.isNotBlank(jpush_alias)){
					MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
					dto.setFpJpushAlias(jpush_alias);
					dto = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
					if(dto!= null && dto.getFpUserId() != null){
						log.info("queryNoticeDate request.getCookies  dto.getFpUserId():"+ dto.getFpUserId());
						paramMap.put("faId", dto.getId());
					}else{
						String lastNewsTime =  (String)MemcacheCacheHelper.mcc.get(jpush_alias+"_lastNewsTime");
						String lastJPushTime =  (String)MemcacheCacheHelper.mcc.get(jpush_alias+"_lastJPushTime");
						if(StringUtils.isBlank(lastNewsTime)){
							lastNewsTime = DateUtil.getDate("yyyy-MM-dd HH:mm:ss");
							MemcacheCacheHelper.mcc.set(jpush_alias+"_lastNewsTime",lastNewsTime);
						}
						if(StringUtils.isBlank(lastJPushTime)){
							lastJPushTime = DateUtil.getDate("yyyy-MM-dd HH:mm:ss");
							MemcacheCacheHelper.mcc.set(jpush_alias+"_lastJPushTime",lastJPushTime);
						}
						
						log.info("queryNoticeDate mcc.get(jpush_alias+_lastNewsTime):"+ lastNewsTime);
						log.info("queryNoticeDate mcc.get(jpush_alias+_lastJPushTime):"+ lastJPushTime);
						paramMap.put("lastNewsTime",lastNewsTime);
						paramMap.put("lastJPushTime",lastJPushTime);
					}

				}
				
			}
			

			
			// 最新公告newsService
			resultMap = newsService.getNewsUpdateDate(paramMap);
			if(null != resultMap){
				result.setAttribute("newsTitle", null == resultMap.get("title")?null:resultMap.get("title"));
				result.setAttribute("newsDate", null == resultMap.get("date")?null:resultMap.get("date"));
				result.setAttribute("newsCount", null == resultMap.get("count")?null:resultMap.get("count"));
			}
			// 极光全员推送消息列表
			resultMap = newsService.getJPushListUpdateDate(paramMap);
			if(null != resultMap){
				result.setAttribute("jPushTitle", null == resultMap.get("title")?null:resultMap.get("title"));
				result.setAttribute("jPushDate", null == resultMap.get("date")?null:resultMap.get("date"));
				result.setAttribute("jPushCount", null == resultMap.get("count")?null:resultMap.get("count"));
			}


			// 三类通知未读总和
			// add 四类通知未读总和
            // add 5类通知未读总和
			result.setAttribute("allCount", ((Long)result.getAttribute("noticeCount")).intValue() 
					+ ((Long)result.getAttribute("jingJiaCount")).intValue() 
					+ ((Long)result.getAttribute("newsCount")).intValue()
					+ ((Long)result.getAttribute("jPushCount")).intValue()
                    + ((Long)result.getAttribute("jPushShopCount")).intValue());
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryNoticeDate error:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}
	
	/**
	 * 理财师工具 - 消息查询
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryShopNoticeDate")
	public ResultMap findShopNoticeDateByFa(HttpServletRequest request, HttpServletResponse response) {
		ResultMap result = new ResultMap();
		try {
			
			UserDTO user = getSession(true).getUser();

			Map<String, Object> paramMap = new HashMap<String, Object>();

			result.setAttribute("noticeCount",new Long(0));
			result.setAttribute("jingJiaCount",new Long(0));
			result.setAttribute("newsCount",new Long(0));
			result.setAttribute("jPushCount",new Long(0));
            result.setAttribute("jPushShopCount",new Long(0));
			
			Map<String, Object> resultMap = new HashMap<String, Object>();
			if(user != null && user.getId()!=null){	//未登录不显示 交易通知 竞价通知
				// 交易通知 不含竞价
				String faId = user.getId();
				paramMap.put("faId", faId);
				
//				resultMap = faNoticeService.getFaOrderNoticeUpdateDateByFa(paramMap);
//				if(null != resultMap){
//					result.setAttribute("noticeTitle", null == resultMap.get("title")?null:resultMap.get("title"));
//					result.setAttribute("noticeDate", null == resultMap.get("date")?null:resultMap.get("date"));
//					result.setAttribute("noticeCount", null == resultMap.get("count")?null:resultMap.get("count"));
//				}
//				// 竞价通知
//				paramMap.put("type", "09");
//				resultMap = faNoticeService.getFaOrderNoticeUpdateDateByFa(paramMap);
//				if(null != resultMap){
//					result.setAttribute("jingJiaTitle", null == resultMap.get("title")?null:resultMap.get("title"));
//					result.setAttribute("jingJiaDate", null == resultMap.get("date")?null:resultMap.get("date"));
//					result.setAttribute("jingJiaCount", null == resultMap.get("count")?null:resultMap.get("count"));
//				}
                // 根据用户查询出绑定的设备标示
                MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
                dto.setFpUserId(faId);
                MessageJpushUserPhoneAliasDTO phoneAlias = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
                if(null != phoneAlias ){
                	//接收参数
                	String fpJpushMsgType = request.getParameter("jMsgTypes");
                	
                	paramMap.put("fpJpushMsgType",fpJpushMsgType);
                	
                    paramMap.put("msgRec",phoneAlias.getFpJpushAliasShop());

                    log.info("queryNoticeDate msgRec :"+phoneAlias.getFpJpushAliasShop());
                }
                // 极光全员推送消息列表-店铺消息
                resultMap = newsService.getJPushListShopUpdateDate(paramMap);
                if(null != resultMap){
                    result.setAttribute("jPushShopTitle", null == resultMap.get("title")?null:resultMap.get("title"));
                    result.setAttribute("jPushShopDate", null == resultMap.get("date")?null:resultMap.get("date"));
                    result.setAttribute("jPushShopCount", null == resultMap.get("count")?null:resultMap.get("count"));
                }

			}else{
				
//				log.info("queryNoticeDate request.getCookies begin!");
//				Cookie[] cookies = request.getCookies();
//				String jpush_alias = "";
//				if(cookies != null){
//					for(Cookie cookie : cookies ){
//						if(Constants.JPUSH_ALIAS.equals(cookie.getName())){
//							jpush_alias = cookie.getValue();
//						}
//					}
//				}
//				log.info("queryNoticeDate JPUSH_ALIAS:"+jpush_alias);
//				if(StringUtils.isNotBlank(jpush_alias)){
//					MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
//					dto.setFpJpushAliasShop(jpush_alias);
//					dto = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
//					if(dto!= null && dto.getFpUserId() != null){
//						log.info("queryNoticeDate request.getCookies  dto.getFpUserId():"+ dto.getFpUserId());
//						paramMap.put("faId", dto.getId());
//					}else{
//						String lastNewsTime =  (String)MemcacheCacheHelper.mcc.get(jpush_alias+"_lastNewsTime");
//						String lastJPushTime =  (String)MemcacheCacheHelper.mcc.get(jpush_alias+"_lastJPushTime");
//						if(StringUtils.isBlank(lastNewsTime)){
//							lastNewsTime = DateUtil.getDate("yyyy-MM-dd HH:mm:ss");
//							MemcacheCacheHelper.mcc.set(jpush_alias+"_lastNewsTime",lastNewsTime);
//						}
//						if(StringUtils.isBlank(lastJPushTime)){
//							lastJPushTime = DateUtil.getDate("yyyy-MM-dd HH:mm:ss");
//							MemcacheCacheHelper.mcc.set(jpush_alias+"_lastJPushTime",lastJPushTime);
//						}
//						
//						log.info("queryNoticeDate mcc.get(jpush_alias+_lastNewsTime):"+ lastNewsTime);
//						log.info("queryNoticeDate mcc.get(jpush_alias+_lastJPushTime):"+ lastJPushTime);
//						paramMap.put("lastNewsTime",lastNewsTime);
//						paramMap.put("lastJPushTime",lastJPushTime);
//					}
//
//				}
				
			}
			

			
			// 最新公告newsService
//			resultMap = newsService.getNewsUpdateDate(paramMap);
//			if(null != resultMap){
//				result.setAttribute("newsTitle", null == resultMap.get("title")?null:resultMap.get("title"));
//				result.setAttribute("newsDate", null == resultMap.get("date")?null:resultMap.get("date"));
//				result.setAttribute("newsCount", null == resultMap.get("count")?null:resultMap.get("count"));
//			}
			// 极光全员推送消息列表
//			resultMap = newsService.getJPushListUpdateDate(paramMap);
//			if(null != resultMap){
//				result.setAttribute("jPushTitle", null == resultMap.get("title")?null:resultMap.get("title"));
//				result.setAttribute("jPushDate", null == resultMap.get("date")?null:resultMap.get("date"));
//				result.setAttribute("jPushCount", null == resultMap.get("count")?null:resultMap.get("count"));
//			}


			// 三类通知未读总和
			// add 四类通知未读总和
            // add 5类通知未读总和
			result.setAttribute("allCount", ((Long)result.getAttribute("noticeCount")).intValue() 
					+ ((Long)result.getAttribute("jingJiaCount")).intValue() 
					+ ((Long)result.getAttribute("newsCount")).intValue()
					+ ((Long)result.getAttribute("jPushCount")).intValue()
                    + ((Long)result.getAttribute("jPushShopCount")).intValue());
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryNoticeDate error:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}
	
	@ResponseBody
	@RequestMapping("clearJPushBadge")
	public ResultMap clearJPushBadge(HttpServletRequest request, HttpServletResponse response,String msgtype) {

		ResultMap result = new ResultMap();

		try {
            log.info("clearJPushBadge msgtype:"+msgtype);

			Map<String, Object> parMap = new HashMap<String, Object>();
			parMap.put("faId", this.getSession().getUser().getId());


			if(StringUtils.isNotBlank(msgtype) && "03".equals(msgtype)){
				// 更新fp_fa_user 中 U_LAST_JPUSH_SHOP_DATE 字段 表示已读消息
				newsService.updateLastJPushListShopDate(parMap);

			}else{

				// 更新fp_fa_user 中 U_LAST_JPUSH_DATE 字段 表示已读消息
				newsService.updateLastJPushListDate(parMap);
			}


			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryNoticeDate error:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}
}
